﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XmlServer.PoolServicer
{
    /// <summary>
    /// The main pool of client requests.  This class accumulates client requests in a collection.
    /// Thread Safe Class
    /// </summary>
    public class ClientPool
    {
        Queue<ClientHandler> pool = null;

        public ClientPool()
            : this(50)
        { }

        public ClientPool(int Capacity)
        {
            pool = new Queue<ClientHandler>(Capacity);
        }


        /// <summary>
        /// Get the number of ClientHandlers in the pool
        /// </summary>
        public int Count
        {
            get
            {
                int count = 0;
                try
                {
                    Monitor.Enter(this);
                    count = pool.Count;
                }
                finally
                {
                    Monitor.Exit(this);
                }
                return count;
            }
        }


        /// <summary>
        /// Add a client handler to the queue/pool
        /// </summary>        
        public void Add(ClientHandler client)
        {
            try
            {
                Monitor.Enter(this);
                pool.Enqueue(client);
            }
            finally
            {
                Monitor.Exit(this);
            }
        }


        /// <summary>
        /// Get the next ClientHandler from the pool/queue that needs to be processed
        /// </summary>        
        public ClientHandler NextClient()
        {
            if (Count == 0) return null;

            ClientHandler client = null;
            try
            {
                Monitor.Enter(this);
                client = pool.Dequeue();
            }
            finally
            {
                Monitor.Exit(this);
            }
            return client;
        }


        /// <summary>
        /// Clear all the ClientHandlers from the pool
        /// </summary>
        public void Clear()
        {

            try
            {
                Monitor.Enter(this);

                ClientHandler client = null;
                do
                {
                    
                    client = NextClient();
                    if (client != null) client.Close();

                } while (client != null);
            }
            finally
            {
                Monitor.Exit(this);
            }
            
        }


    }

}
